import socketserver
import json
import os
import hashlib


class MyTCPHandle(socketserver.BaseRequestHandler):
    with open('../conf/users', 'r') as f_user:
        users = json.load(f_user)

    home_dir = '/root/ftp_home/'

    def user_auth(self, data):
        u_name = data['name']
        u_pwd = data['pwd']

        if u_name in self.users.keys():
            m = hashlib.md5()
            m.update(self.users[u_name]['pwd'].encode())
            m_pwd = m.hexdigest()
            if m_pwd == u_pwd:
                data['status'] = '200'
            else:
                data['status'] = '403'
            s_data = json.dumps(data).encode()
            self.request.send(s_data)
        else:
            data['status'] = '404'
            s_data = json.dumps(data).encode()
            self.request.send(s_data)

    def cmd_ls(self, data):
        ls_dir = self.home_dir+data['dir']
        files = os.listdir(ls_dir)
        result = json.dumps(files).encode()
        self.request.send(result)

    def cmd_cd(self, data):
        verify_dir = self.home_dir+data['cur_dir']+'/'+data['go_dir']
        if os.path.isdir(verify_dir):
            data['status'] = '200'
        else:
            data['status'] = '404'

        result = json.dumps(data).encode()
        self.request.send(result)

    def cmd_mkdir(self, data):
        verify_dir = self.home_dir + data['cur_dir'] + '/' + data['create_dir']
        if os.path.isdir(verify_dir):
            data['status'] = '403'
        else:
            try:
                os.mkdir(verify_dir)
                data['status'] = '200'
            except FileNotFoundError as e:
                data['status'] = '404'

        result = json.dumps(data).encode()
        self.request.send(result)

    def handle(self):
        while True:
            cmd = self.request.recv(1024).strip()
            if len(cmd) == 0:
                print(self.client_address, '已断开连接')
                break

            # 解析数据, 交给对应方法处理
            cmd_str = json.loads(cmd.decode())
            if hasattr(self, cmd_str['form']):
                func = getattr(self, cmd_str['form'])
                func(cmd_str)



if __name__ == '__main__':
    ip, port = 'localhost', 9999
    server = socketserver.ThreadingTCPServer((ip, port), MyTCPHandle)
    server.serve_forever()